<template>
  <div class="establishId">
    <div class="max">
      <a-form-model ref="ruleForm" :model="formInfo" trim='' :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" hideRequiredMark>
        <a-form-model-item label="企业名称" v-if="currentType !== 1">
          <a-input v-model="formInfo.tenantName" placeholder="企业名称和营业执照名称一致，否则审核不通过" />
          <div :class="{'hint': true, 'hintcolor': !tenantNameStatus}"> {{tenantNametext}}</div>
        </a-form-model-item>
        <a-form-model-item label="统一社会信用代码" prop="creditCode" v-if="currentType !== 1">
          <a-input v-model="formInfo.creditCode" placeholder="营业执照上的统一社会信用代码，否则审核不通过" />
        </a-form-model-item>
        <a-form-model-item label="联系人" prop="contact" v-if="currentType !== 1">
          <a-input v-model="formInfo.contact" placeholder="请输入联系人全名，2-10个汉字" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="userPhone">
          <a-input v-model="formInfo.userPhone" placeholder="请输入手机号" @blur="userPhoneBlur" />
        </a-form-model-item>
        <a-form-model-item label="短信验证码" prop="smsCode">
          <div class="sms-code">
            <a-input type="number" :max-length="6" v-model="formInfo.smsCode" placeholder="请输入短信验证码" />
            <div class="right-options">
              <div class="option-content" @click="sendSmsTab" v-if="countDown === 0">
                <span>获取验证码</span>
              </div>
              <div class="count-down" v-else>
                <span>{{countDown}}s</span>
              </div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password" v-if="currentType !== 1">
          <a-input v-model="formInfo.password" placeholder="请输入8-20个字符，必须包含字母和数字" />
        </a-form-model-item>
        <a-form-model-item label="确认密码" prop="passwordOK" v-if="currentType !== 1">
          <a-input v-model="formInfo.passwordOK" placeholder="请再次输入密码" />
        </a-form-model-item>
        <div class="white-area" v-if="currentType === 1"></div>
        <a-row style="padding-left:240px">
          <a-col :span="5"></a-col>
          <a-col :span="10">
            <div class="checkeds">
              <a-checkbox :checked="formInfo.isAgree" @change="onChange">
                我已阅读并同意 <a href="">《迅车通平台用户使用许可》、</a> <a href="">《弘巽隐私政策》</a>
              </a-checkbox>
            </div>
          </a-col>
        </a-row>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <div class="clicks" @click="skip">下一步</div>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!--验证码-->
    <verification-code v-model="verificationDialog" v-if="verificationDialog" @confirmDialog="confirmDialog"></verification-code>
  </div>
</template>
<script>
import verificationCode from '@/components/verificationCode'
export default {
  components: { verificationCode },
  data() {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 10 },
      //企业名称是否有值
      tenantNameStatus: true,
      tenantNametext: '请填写营业执照上登记的公司名称，冒用其他公司名称属于违规行为',
      // 页面表单数据
      formInfo: {
        tenantName: '',
        creditCode: '',
        contact: '',
        userPhone: '',
        smsCode: '',
        name: '',
        password: '',
        passwordOK: '',
        isAgree: true
      },
      // 当前倒计时的时间
      countDown: 0,
      // 倒计时时间
      countDownTime: 60,
        //图片验证码弹框
      verificationDialog:false,
      // 图片二维码的值
      verification: '',
      // 图片二维码的key
      imgKey: '',
      // 防重复点击操作
      isTap: false
    }
  },
  mounted() {
  },
  methods: {
    // 手机号离焦事件
    userPhoneBlur() {
      if (this.checkPhoneNum(this.formInfo.userPhone)) {
        this.$store.dispatch('settleIn/validateAccountOfPhone', {
          phone: this.formInfo.userPhone
        }).then(result => {
          console.log(result)
          if (result.hasAccount) {
            this.$honexunMessage('提示', '该手机号已被注册，请直接登陆该手机号或使用其他手机号进行注册。');
          }
        })
      }
    },
    // 发送手机验证码
    sendSmsTab() {
      if (!this.checkPhoneNum(this.formInfo.userPhone)) {
        this.$message.error('请输入正确的手机号');
        return;
      }
      this.verificationDialog = true
    },
    // 输入验证码弹框确认
    confirmDialog(data){
        this.verification = data.verification
        this.imgKey = data.imgKey
        let params = {
            code: this.verification,
            key: this.imgKey,
            mobile: this.formInfo.userPhone
        }
        this.sendSmsCode(params);
        this.startCountDown(this.countDownTime);
    },
    // 发送短信验证码
    sendSmsCode(data) {
      this.$store.dispatch('request', this.$api.register.sendSms(data)).then(res => {
        if (res.success) {
          this.$message.success('手机验证码发送成功');
        }
      })
    },
    // 验证手机号
    checkPhoneNum(value) {
      let myreg = /^1[3|4|5|6|7|8|9][0-9]{1}[0-9]{8}$/;
      return myreg.test(value);
    },
    // 开始倒计时
    startCountDown(m) {
      this.countDown = m;
      if (m > 0) {
        let timer = setTimeout(() => {
          this.startCountDown(m - 1);
          clearTimeout(timer);
        }, 1000);
      }
    },
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //是否勾选
    onChange(e) {
      this.formInfo.isAgree = e.target.checked
    },
    //下一步跳转
    skip() {
      if (this.isTap) return;
      this.isTap = true;
      let timer = setTimeout(() => {
        this.isTap = false;
        clearTimeout(timer);
      }, 2000)

      if (!this.formInfo.isAgree) {
        this.$message.error('请先阅读并同意协议之后进行下一步操作');
        return
      }
      if (this.formInfo.tenantName === '') {
        this.tenantNametext = '请输入企业名称'
        this.tenantNameStatus = false
      } else {
        this.tenantNametext = '请填写营业执照上登记的公司名称，冒用其他公司名称属于违规行为'
        this.tenantNameStatus = true
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.currentType === 1) {
            //企业认证2s
            this.register2s();
          } else {
            //企业认证-4s /供应商
            this.register4s();
          }
        } else {
          this.$message.error('请先填写完上方表单的数据再进行下一步操作')
        }
      });

    },
    // 2s注册
    register2s() {
      let data = {
        mobile: this.formInfo.userPhone,
        smsCode: this.formInfo.smsCode
      };
      this.$store.dispatch('settleIn/validateAccountOfPhone', {
        phone: data.mobile
      }).then(result => {
        if (!result.hasAccount) {
          this.$store.dispatch('request', this.$api.register.register2s(data)).then(res => {
            this.$store.commit('user/setToken', res.result);
            this.$router.push('/enter/enterView/firmApprove2s');
          })
        } else {
          this.$honexunMessage('提示', '该手机号已被注册，请直接登陆该手机号或使用其他手机号进行注册。');
        }
      });

    },
    //4s 注册/供货商注册
    register4s() {
      this.formInfo.mobile = this.formInfo.userPhone
      var url = ''
      if (this.currentType === 2) {
        url = this.$api.register.register4s(this.formInfo)
      } else {
        url = this.$api.register.registerSupplier(this.formInfo)
      }
      this.$store.dispatch('request', url).then(res => {
        console.log(res);
        this.$store.commit('user/setToken', res.result);
        this.$router.push('/enter/enterView/supplier');
      })
    },
    //供货商注册
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
  },
  computed: {
    currentType() {
      return this.$store.state.settleIn.currentType
    },
    rules() {
      if (this.currentType !== 1) {
        return {
          tenantName: [{ required: true, message: '请输入企业名称' }],
          creditCode: [{ required: true, message: '请输入统一社会信用代码' }],
          contact: [{ required: true, message: '请输入联系人' }, { pattern: /^[\u4E00-\u9FA5]{1,100}$/, message: '请输入汉字' }, {
            validator: (rule, value, callback) => {
              console.log(value);
              if (value.length < 2 || value.length > 8) {
                callback('请输入2-8个汉字')
              } else {
                callback();
              }
            },
          }],
          userPhone: [{ required: true, message: '请输入手机号' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }],
          smsCode: [{ required: true, message: '请输入验证码' }],
          password: [{ required: true, message: '请输入密码' }, { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/, message: '请输入8-20个字符，必须包含数字和字母' }],
          passwordOK: [{ required: true, message: '请再次输入密码' }, {
            validator: (rule, value, callback) => {
              console.log(value);
              if (this.formInfo.password && this.formInfo.password !== value) {
                callback('两次密码输入不一致！')
              } else {
                callback();
              }
            },
          },],

        }
      } else {
        return {
          userPhone: [{ required: true, message: '请输入手机号' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }],
          smsCode: [{ required: true, message: '请输入验证码' }]
        }
      }
    }
  },
  created() {
    // this.form = this.$form.createForm(this, { name: 'register' });
  }
}
</script>
<style lang="less" scoped>
.establishId {
  width: 100%;
  margin: 0 auto;

  a {
    color: #3b82ff;
  }

  .max {
    margin-top: 40px;

    .sms-code {
      position: relative;

      .right-options {
        position: absolute;
        height: 12px;
        line-height: 12px;
        font-size: 12px;
        top: 0;
        bottom: 0;
        margin: auto;
        right: 22px;

        .count-down {
          color: #3b82ff;
          opacity: 0.3;
          width: 60px;
          text-align: center;
          .userUnSelect();
        }

        .option-content {
          .count-down();
          cursor: pointer;
        }
      }
    }

    .white-area {
      height: 200px;
    }

    .ant-form-item {
      padding-left: 240px;
      position: relative;

      label {
        font-size: 12px;
        color: @colorGreyFont;
      }
      .hint {
        color: #ff9900;
        font-size: 12px;
        position: absolute;
        top: 14px;
      }
      .checkeds {
        margin-left: 200px;
      }
      .clicks {
        width: 300px;
        height: 40px;
        opacity: 1;
        background: @activeRed;
        border-radius: 2px;
        text-align: center;
        line-height: 40px;
        color: #fff;
        font-size: 14px;
        margin: 30px 0 36px 44px;
        cursor: pointer;
      }
    }
  }
  .hintcolor {
    color: #f5222d !important;
    font-size: 14px !important;
  }
}
</style>
